**** Average portfolio share out of country n
preserve
keep fundid country datem zint lzint
compress
*******************************************************************************
* set variables
bys fundid datem: egen sum_ = total(zint), m // sum portfolio share
bys fundid datem: egen lsum_ = total(lzint), m // sum lag portfolio share

* initiate variables
levelsof country, local(country)
foreach c of local country {
	gen z_`c' = .
	gen lz_`c' = .
}
*******************************************************************************

*******************************************************************************
* Normalization
levelsof country, local(country)
foreach c of local country {
	display as text "`c'"
	
	* sum of the weights when country c is not included. problem is
	* if the fund does invest in c, then the sum is "full". Sum over c
	bys fundid datem: egen sum_`c' = total(zint) if country != "`c'", m
	bys fundid datem: egen lsum_`c' = total(lzint) if country != "`c'", m
	
	* normalization
	qui replace z_`c' = zint / sum_`c'
	qui replace lz_`c' = lzint / lsum_`c'

	* if fund does not invest in c, then missing value
	qui replace z_`c' = . if sum_ == sum_`c'
	qui replace lz_`c' = . if lsum_ == lsum_`c'
	
	* average
	bys fundid country (datem) : egen zbar_`c' = mean(z_`c') if !mi(z_`c')
}
keep fundid country datem zbar_* z_* lz_*
*******************************************************************************

save "$datapath/Portfolio_Paper_zbar", replace
restore 